package com.twu.biblioteca.model;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by sgreweni on 30.07.14.
 */
public class Library<T extends LibraryItem> {
    private final Map<T, Boolean> items = new HashMap<>();

    public Collection<T> allAvailableItems() {
        Collection<T> availableItems = items.keySet().stream().filter(item -> items.get(item)).collect(Collectors.toCollection(() -> new LinkedList<>()));
        return availableItems;
    }

    public Optional<T> checkoutItem(T item) {
        Optional<T> result = findItem(item);
        if(result.isPresent()){
            items.put(item, false);
        }
        return result;
    }

    public Optional<T> returnItem(T item) {
        Optional<T> result = findItem(item);
        if(result.isPresent()){
            items.put(item, true);
        }
        return result;
    }

    public Optional<T> findItemByTitle(String title) {
        return items.keySet().stream()
                .filter(item -> item.getTitle().equals(title))
                .findFirst();
    }

    private Optional<T> findItem(T item){
        Stream<T> filter = items.keySet().stream().filter(b -> {
            if (item == null) {
                return false;
            }
            if (!items.containsKey(item)) {
                return false;
            }
            return items.get(item);
        });

        return filter.findFirst();
    }

    public void addItem(T item){
        items.put(item, true);
    }

    public Map<T, Boolean> getItems() {
        return items;
    }
}
